import createNextStore from "./index";
import React from 'react'
const __NEXT_REDUX_STORE = "__NEXT_REDUX_STORE"; //定义个变量用来查看客户端是否存在store
import { getNewsTypesList } from '@/server/news'
import { pinyin } from 'pinyin-pro';
import { navData } from './navData'
import { videoBackNavList } from '@/common/enum'
let homeNavData = {
  basketballBackVideoNavList: [],
  footballBackVideoNavList: [],
  newsNavList: [],
  navData: [],
}


//根据不同场景进行创建或者返回现有store
function getOrCreateStore (initialState) {
  const isServer = typeof window === "undefined";
  if (isServer) {
    // 服务端
    // 返回新的store
    return createNextStore(initialState);
  }

  if (!window[__NEXT_REDUX_STORE]) {
    // console.log('XXX')
    // 是客户端客户端没有store create
    window[__NEXT_REDUX_STORE] = createNextStore(initialState);
  }
  return window[__NEXT_REDUX_STORE];
}
const withRedux = (Comp) => {
  // 高阶组件，让每个app都经历高阶组件进行处理集成redux
  return class HocReducerComp extends React.Component {
    constructor(props) {
      super(props);
      this.ReduxStore = getOrCreateStore(props.initialState);
    }
    static async getInitialProps (ctx) {
      try {
        const data = [...navData]
        const setDataAction = (type, res) => {
          data.forEach((row, index) => {
            if (row?.key === type) {
              row.nav = res
            }
          })
        }
        let [newsNavList] = await Promise.all([getNewsTypesList()])
        newsNavList = newsNavList.map(row => ({ ...row, en: pinyin(row?.newsTypeName, { toneType: 'none', type: "array" }).join("") }))
        setDataAction(4, videoBackNavList.b)
        setDataAction(3, videoBackNavList.f)
        let list = [...newsNavList]
        list = list.map(r => ({ ...r, typeName: r.newsTypeName }))
        setDataAction(5, list)
        homeNavData = {
          basketballBackVideoNavList: videoBackNavList.b,
          footballBackVideoNavList: videoBackNavList.f,
          newsNavList,
          navData: data,
        }
      } catch (error) {
        console.log(error, 'Redux')
      }
      const MyStore = getOrCreateStore({ home: homeNavData });
      /* 利用ctx把store传入App，在App中进行store的初始化 */
      ctx.ReduxStore = MyStore;
      let appProps = {};
      if (typeof Comp.getInitialProps === 'function') {
        appProps = await Comp.getInitialProps(ctx);
      }
      // 这里都是在服务端重新注入数据
      return { ...appProps, initialState: MyStore.getState() };
    }
    render () {
      return <Comp {...this.props} ReduxStore={this.ReduxStore} />;
    }
  }
};
export default withRedux;